<template>
	<view id="topBox">
		<z-nav-bar title="授课列表"></z-nav-bar>
		<view class="top-box">
			<view class="flex_sbc">
				<uni-datetime-picker
					type="date"
					:clear-icon="false"
					v-model="single"
					return-type="string"
					@change="dateChange"
				>
					<view class="flex_fsc">
						<view class="z-font-32 text-w">{{ displaySingle }}</view>
						<view class="down-item flex_cc">
							<uni-icons type="bottom" size="16" color="#999999"></uni-icons>
						</view>
					</view>
				</uni-datetime-picker>
				<view v-if="startState == 1" class="make-appointment" @click="lectureAppointment">预约授课</view>
			</view>
			<view class="flex_sbc uni-mt-56">
				<view v-for="(item, index) in dayList" :key="index" class="text-c" @click="getDayCourse(item.day)">
					<view :class="[selectDay === item.day ? 'uni-orange' : 'color-C4C7CC']">
						{{ singleDay === item.day ? '今天' : item.week }}
					</view>
					<view class="day-num" :class="{ 'uni-orange-bg uni-white': selectDay === item.day }">
						{{ item.day }}
					</view>
				</view>
			</view>
		</view>
	</view>
	<scroll-view
		scroll-y
		:style="{ height: svHeight }"
		refresher-enabled="true"
		:refresher-triggered="triggered"
		:refresher-threshold="100"
		@refresherrefresh="onRefresh"
		@refresherrestore="onRestore"
		@scrolltolower="getNextPage"
	>
		<view v-if="data.list.length">
			<view v-for="(item, index) in data.list" :key="index" class="item-box" @click="teachButton(index)">
				<view class="flex_sbc">
					<view class="flex_fsc">
						<view class="z-font-36 text-w">{{ item.beginTime.split(' ')[1].split(':').slice(0, 2).join(':') }}</view>
						<view v-if="item.status" class="status uni-color-main-grey uni-F5F5F5-bg">已完成</view>
						<view v-else-if="nowTimeStamp >= item.beginTimeStamp" class="status uni-red FFF0F0-bg">
							已逾期
						</view>
						<view v-else class="status uni-color-main-grey uni-F5F5F5-bg">未开始</view>
					</view>
					<view class="button uni-white uni-color-main-bg">
						{{ item.status || startState == 2 ? '查看' : '授课' }}
					</view>
				</view>
				<view class="flex_fsc uni-mt-42">
					<image :src="setting.oss_pub_domain + item.studentAvatar" class="user-head"></image>
					<view>
						<view class="z-font-24 uni-color-grey flex_fsc">
							<view class="u-line-1" style="max-width: 200rpx">{{ item.studentName }}</view>
							<view class="uni-mx-16">|</view>
							<view>{{ item.hisAvg }}</view>
						</view>
						<view class="z-font-32 uni-mt-14 u-line-1">{{ item.name }}</view>
					</view>
				</view>
			</view>
		</view>
		<z-no-data v-else></z-no-data>
	</scroll-view>
</template>

<script setup>
import { appointmentGiveLessonsList, appointmentGiveLessonsDetail } from '@/api/course.js';
import { getPlayerDetial } from '@/api/player.js'
import { onShow } from '@dcloudio/uni-app';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
const { proxy: that } = getCurrentInstance(), startState = uni.getStorageSync('start-state');

const nowTimeStamp = Date.parse(new Date());

// 下拉刷新
const triggered = ref('restore');
let _freshing = false;
function onRefresh() {
	if (_freshing) return;
	_freshing = true;
	data.pageNum = 1;
	fetchData();
}
function onRestore() {
	triggered.value = 'restore';
}

function getNextPage() {
	if (data.list.length >= data.total) return;
	data.pageNum += 1;
	fetchData();
}

// 获取数据
const data = reactive({
	beginTime: '',
	list: [],
	pageNum: 1,
	pageSize: 10,
	total: 0
});

function getDayCourse(day) {
	if (selectDay.value === day) return;
	selectDay.value = day;
	data.beginTime = `${displaySingle.value}${selectDay.value}`.replace('年', '-').replace('月', '-');
	fetchData();
}

function fetchData() {
	appointmentGiveLessonsList({ beginTime: data.beginTime }).then((res) => {
		res.rows.forEach((item) => {
			item.beginTimeStamp = Date.parse(item.beginTime);
		});
		if (data.pageNum === 1) data.list = res.rows || [];
		else data.list.push(...res.rows);
		data.total = res.total || 0;
		triggered.value = false;
		_freshing = false;
	});
}

// 预约授课
function lectureAppointment() {
	uni.navigateTo({
		url: '/pages/player/teach-order/teach-order',
		events: {
			done() {
				data.pageNum = 1;
				fetchData();
			}
		}
	});
}

// 授课按钮
async function teachButton(index) {
	const item = data.list[index];
	uni.showLoading({
		title: '正在获取课程信息'
	})
	const playerInfo = await getPlayerDetial(item.studentId)
	uni.setStorageSync('player-info', playerInfo);
	appointmentGiveLessonsDetail(item.courseId).then((res) => {
		res.result = JSON.parse(res.result)
		uni.setStorageSync('edit-course', res);
		uni.hideLoading()
		uni.navigateTo({
			url: '/pages/course/details/details'
		});
	}).catch(() => {
		uni.hideLoading()
	});
}

// 顶部日历
const single = ref(''),
	displaySingle = ref(''),
	dayList = reactive([{}]),
	date = new Date(),
	singleDay = date.getDate().toString().padStart(2, '0'),
	tmpDay = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
		.getDate()
		.toString()
		.padStart(2, '0')}`,
	selectDay = ref('');
single.value = tmpDay;
dateChange(tmpDay);

function dateChange(e) {
	const weeks = ['日', '一', '二', '三', '四', '五', '六'];
	e = e.split('-');
	displaySingle.value = `${e[0]}年${e[1]}月`;
	getDayCourse(single.value.split('-').reverse()[0]);
	const tmpDay = new Date(single.value);
	const startDay = getNextDate(single.value, -tmpDay.getDay());
	dayList.length = 0;
	for (var i = 0; i < 7; i++) {
		dayList.push({
			day: getNextDate(startDay, i).split('-').reverse()[0],
			week: '周' + weeks[i]
		});
	}
}

function getNextDate(date, day) {
	const dd = new Date(date);
	dd.setDate(dd.getDate() + day);
	const y = dd.getFullYear();
	const m = (dd.getMonth() + 1).toString().padStart(2, '0');
	const d = dd.getDate().toString().padStart(2, '0');
	return y + '-' + m + '-' + d;
}

// 计算底部滚动窗口高度
const svHeight = ref('100vh');
onMounted(() => {
	uni.createSelectorQuery()
		.select('#topBox')
		.boundingClientRect((data) => {
			svHeight.value = `calc(100vh - ${data.bottom}px)`;
		})
		.exec();
});
</script>

<style lang="scss">
@import 'schedule.scss';
</style>